import SnowflakeId from "snowflake-id";
const { Op } = require("sequelize");
const CourseTypeModels = require('../models/course_type');

interface courseType {
    id?: number
    type: string
}

class CourseTypeService {
    // 获取课程类型列表
    public async getTypes() {
        const res: any = await CourseTypeModels.findAndCountAll()
        return res ? res : null
    }
    // 分页获取课程类型列表
    public async getTypesByPage(pageNum: number, pageSize: number) {
        const offset = (pageNum - 1) * pageSize
        const { count, rows } = await CourseTypeModels.findAndCountAll({
            offset: offset,
            limit: pageSize * 1
        })
        return {
            pageNum,
            pageSize,
            total: count,
            list: rows
        }
    }
    // 根据关键词搜索课程类型列表
    public async getCoursetypeByname(keyword: string) {
        // 不分页直接获取
        const { count, rows } = await CourseTypeModels.findAndCountAll({
            where: {
                type: {
                    [Op.like]: `%${keyword}%`,
                }
            }
        })
        return {
            total: count,
            list: rows
        }
    }
    // 分页获取-根据关键词搜索课程类型列表
    public async geTypeBynameandPage(pageNum: number, pageSize: number, keyword: string) {
        const offset = (pageNum - 1) * pageSize
        const { count, rows } = await CourseTypeModels.findAndCountAll({
            where: {
                type: {
                    [Op.like]: `%${keyword}%`,
                }
            },
            offset: offset,
            limit: pageSize * 1
        })
        return {
            pageNum,
            pageSize,
            total: count,
            list: rows
        }
    }
    // 根据id获取课程类型
    public async getInfoById(id: number) {
        const res = await CourseTypeModels.findOne({
            where: {
                id
            }
        })
        return res? res.dataValues : null
    }
    // 添加课程类型
    public async createCourseType(params: courseType) {
        const id = new SnowflakeId();
        const temp = id.generate() + ''
        params.id = +(temp.slice(temp.length - 7));
        const res: any = await CourseTypeModels.create(params)
        return res ? res.dataValues : null;
    }
    // 更新课程类型
    public async update(id: number, params: courseType) {
        const whereOpt = { id }
        const res = await CourseTypeModels.update(params, { where: whereOpt })
        return res[0] > 0
    }
    // 删除课程类型
    public async deleteType(id: number) {
        const res: any = await CourseTypeModels.destroy({
            where: { id }
        })
        return res > 0
    }
}

module.exports = new CourseTypeService()
// 解决同目录下多个ts文件都引入Op,会报错的问题
export { }